import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sonora/bloc/home/sj_home_bloc.dart';
import 'package:sonora/bloc/home/sj_home_event.dart';
import 'package:sonora/bloc/home/sj_home_state.dart';
import 'package:sonora/config/sj_app_initial.dart';
import 'package:sonora/events/sj_works_event.dart';
import 'package:sonora/models/sj_broad_caster_data.dart';
import 'package:sonora/models/sj_works_model.dart';
import 'package:sonora/shared/lib/constants/sj_colors.dart';
import 'package:sonora/utils/sj_text_style.dart';
import 'package:sonora/utils/sj_utils.dart';
import 'package:sonora/views/navigation/routes/sj_app_router.dart';

@RoutePage()
class SjHomePage extends StatefulWidget {
  const SjHomePage({super.key});

  @override
  State<SjHomePage> createState() => _SjHomePageState();
}

class _SjHomePageState extends State<SjHomePage>
    with AutomaticKeepAliveClientMixin {
  late SjHomeBloc _homeBloc;
  late final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    _homeBloc = getit<SjHomeBloc>();
    eventBus.on<SjWorksBusEvent>().listen((event) {
      _homeBloc.add(SjHomeEvent.loadedWallSearch(callback: () {}));
    });
  }

  @override
  void dispose() {
    // _homeBloc.close();
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return BlocProvider<SjHomeBloc>.value(
        value: _homeBloc..add(SjHomeEventInitial(context: context)),
        child: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/home_bg.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: Column(
            children: [
              Image.asset(
                'assets/images/home_top_banner.png',
                width: MediaQuery.of(context).size.width,
                fit: BoxFit.cover,
              ),
              const SizedBox(
                height: 12,
              ),
              Container(
                  width: double.infinity,
                  height: 90,
                  decoration: const BoxDecoration(color: Color(0x80FF5FB7)),
                  padding: const EdgeInsets.symmetric(
                    vertical: 6,
                  ),
                  child: BlocBuilder<SjHomeBloc, SjHomeState>(
                    builder: (context, state) {
                      return ListView.builder(
                        itemBuilder: (context, index) {
                          return _buildAvatar(
                              state.randomWallList?.elementAt(index),
                              index,
                              state.randomWallList?.length ?? 0);
                        },
                        itemCount: state.randomWallList?.length ?? 0,
                        scrollDirection: Axis.horizontal,
                      );
                    },
                  )),
              Expanded(
                  child: Stack(
                children: [
                  Padding(
                      padding: const EdgeInsets.only(left: 10, right: 10),
                      child: BlocBuilder<SjHomeBloc, SjHomeState>(
                          builder: (context, state) {
                        return SmartRefresher(
                            enablePullDown: true,
                            controller: _refreshController,
                            onRefresh: () {
                              _homeBloc.add(
                                  SjHomeEvent.loadedWallSearch(callback: () {
                                _refreshController.refreshCompleted();
                              }));
                            },
                            child: MasonryGridView.count(
                              crossAxisCount: 2,
                              // 设置列数
                              mainAxisSpacing: 8,
                              crossAxisSpacing: 8,
                              itemCount: state.worksList?.length ?? 0,
                              padding: const EdgeInsets.only(
                                  left: 0, top: 10, right: 0, bottom: 10),
                              itemBuilder: (context, index) {
                                SjWorksModel? data =
                                    state.worksList?.elementAt(index);
                                return GestureDetector(
                                    onTap: () {
                                      context.router.push(
                                          SjArticleDetailRoute(data: data!));
                                    },
                                    child: index == 1
                                        ? _buildContentCard(data, index)
                                        : _buildContentCard1(data, index));
                              },
                            ));
                      })),
                  Positioned(
                    right: 10,
                    bottom: 47,
                    child: Ink(
                      child: InkWell(
                          onTap: () {
                            context.router.push(const SjArticlePublishRoute());
                          },
                          child: Image.asset('assets/images/home_edit.png')),
                    ),
                  )
                ],
              )),
            ],
          ),
        ));
  }

  Widget _buildAvatar(SjBroadCasterData? data, int index, int count) {
    return (count == 0 || data == null)
        ? Container()
        : GestureDetector(
            onTap: () {
              context.router.push(SjOtherProfileRoute(broadCaster: data));
            },
            child: Container(
              margin: index == count - 1
                  ? const EdgeInsets.only(left: 24, right: 20)
                  : (index == 0
                      ? const EdgeInsets.only(left: 20)
                      : const EdgeInsets.only(left: 24)),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    width: 52, // Diameter (2 * radius) = 2 * 15
                    height: 52, // Diameter (2 * radius) = 2 * 15
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      image: DecorationImage(
                        image: NetworkImage(data.avatar ??
                            ''), // Replace with your avatar image URL
                        fit: BoxFit.cover,
                      ),
                      border: Border.all(
                        color: Colors.black, // Border color
                        width: 1, // Border width
                      ),
                      boxShadow: const [
                        BoxShadow(
                          color: Colors.white, // Shadow color and opacity
                          offset: Offset(1, 1), // Shadow offset (x, y)
                        ),
                      ],
                    ),
                  ),
                  Text(SjUtils.recommendNickname(data.nickname),
                      style: SjTextStyle.customFontBlack12),
                ],
              ),
            ));
  }

  Widget _buildContentCard(SjWorksModel? data, int index) {
    return Column(
      children: [
        Image.asset('assets/images/home_hot_icon.png'),
        Padding(
            padding: const EdgeInsets.all(2),
            child: Stack(
              children: [
                Container(
                  padding: const EdgeInsets.all(3),
                  decoration: const BoxDecoration(
                      color: SjColors.blackColor,
                      boxShadow: [
                        BoxShadow(
                            color: SjColors.iconWhiteColor,
                            offset: Offset(2, 2))
                      ]),
                  child: Container(
                    padding: const EdgeInsets.all(14.0),
                    width: double.infinity,
                    height: 215,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(data?.cover ?? ''),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                ),
                Positioned(
                  top: 8,
                  right: 8,
                  width: 28,
                  height: 28,
                  child: InkWell(
                    child: (data?.isLiked == null || data?.isLiked! == false)
                        ? Image.asset('assets/images/home_un_like.png')
                        : Image.asset('assets/images/home_like.png'),
                    onTap: () {
                      _homeBloc.add(SjHomeEventClickLikeButton(
                          data?.isLiked ?? false, data?.worksId ?? ''));
                    },
                  ),
                ),
                Positioned(
                  left: 0,
                  bottom: 0,
                  child: Stack(
                    children: [
                      Positioned.fill(
                        left: 0,
                        bottom: 0,
                        child: Container(
                          height: 17,
                          decoration: const BoxDecoration(
                              image: DecorationImage(
                                  // alignment: Alignment.bottomLeft,
                                  image: AssetImage(
                                      'assets/images/home_name_bg.png'),
                                  fit: BoxFit.fitWidth)),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 5),
                        child: Container(
                          width: 30, // Diameter (2 * radius) = 2 * 15
                          height: 30, // Diameter (2 * radius) = 2 * 15
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            image: DecorationImage(
                              image: NetworkImage(data?.avatar ??
                                  ''), // Replace with your avatar image URL
                              fit: BoxFit.cover,
                            ),
                            border: Border.all(
                              color: Colors.black, // Border color
                              width: 1, // Border width
                            ),
                            boxShadow: const [
                              BoxShadow(
                                color: Colors.white, // Shadow color and opacity
                                offset: Offset(1, 1), // Shadow offset (x, y)
                              ),
                            ],
                          ),
                        ),
                      ),
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          const SizedBox(
                            width: 35,
                          ),
                          Text(
                            data?.nickname ?? '',
                            style: SjTextStyle.customFontBlack24,
                          )
                        ],
                      )
                    ],
                  ),
                )
              ],
            ))
      ],
    );
  }

  Widget _buildContentCard1(SjWorksModel? data, index) {
    return Padding(
        padding: const EdgeInsets.all(2),
        child: Stack(
          children: [
            Container(
              padding: const EdgeInsets.all(3),
              decoration:
                  const BoxDecoration(color: SjColors.blackColor, boxShadow: [
                BoxShadow(color: SjColors.iconWhiteColor, offset: Offset(2, 2))
              ]),
              child: Container(
                padding: const EdgeInsets.all(14.0),
                width: double.infinity,
                height: 215,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage(data?.cover ?? ''),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),
            Positioned(
              top: 8,
              right: 8,
              width: 28,
              height: 28,
              child: InkWell(
                child: (data?.isLiked == null || data?.isLiked! == false)
                    ? Image.asset('assets/images/home_un_like.png')
                    : Image.asset('assets/images/home_like.png'),
                onTap: () {
                  _homeBloc.add(SjHomeEventClickLikeButton(
                      data?.isLiked ?? false, data?.worksId ?? ''));
                },
              ),
            ),
            Positioned(
              left: 0,
              bottom: 0,
              child: Stack(
                children: [
                  Positioned.fill(
                    left: 0,
                    bottom: 0,
                    child: Container(
                      height: 17,
                      decoration: const BoxDecoration(
                          image: DecorationImage(
                              // alignment: Alignment.bottomLeft,
                              image:
                                  AssetImage('assets/images/home_name_bg.png'),
                              fit: BoxFit.fitWidth)),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 5),
                    child: Container(
                      width: 30, // Diameter (2 * radius) = 2 * 15
                      height: 30, // Diameter (2 * radius) = 2 * 15
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        image: DecorationImage(
                          image: NetworkImage(data?.avatar ??
                              ''), // Replace with your avatar image URL
                          fit: BoxFit.cover,
                        ),
                        border: Border.all(
                          color: Colors.black, // Border color
                          width: 1, // Border width
                        ),
                        boxShadow: const [
                          BoxShadow(
                            color: Colors.white, // Shadow color and opacity
                            offset: Offset(1, 1), // Shadow offset (x, y)
                          ),
                        ],
                      ),
                    ),
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      const SizedBox(
                        width: 35,
                      ),
                      Text(
                        data?.nickname ?? '',
                        style: SjTextStyle.customFontBlack24,
                      )
                    ],
                  )
                ],
              ),
            )
          ],
        ));
  }
}
